package com.zy.baselib

import android.os.Bundle
import android.view.View
import com.sudworth.themvp.model.IModel
import com.sudworth.themvp.presenter.FragmentPresenter
import com.sudworth.themvp.tools.ObjectInstanceManager
import com.sudworth.themvp.view.IDelegate
import com.violet.constlib.exception.ExceptionHandle
import com.zy.baselib.widget.LoadingDialog
import java.util.*

abstract class BaseDiVMStub<V : IDelegate, M : IModel>: FragmentPresenter<V, M>(), IDisplay {

    /**
     * 让带有@AgainInstance 注解的 field 在app意外杀死重启后可以自动重新实例化
     */
    private var mObjectInstanceManager = ObjectInstanceManager()

    private var mLoadingDialog: LoadingDialog? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mLoadingDialog = LoadingDialog(requireContext())
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        if (savedInstanceState == null) {
            onInitData()
        } else {
            resetData(savedInstanceState)
        }
    }

    protected open fun onInitData() {
        initData()
    }

    override fun initData() {}

    override fun resetData(savedInstanceState: Bundle) {
        mObjectInstanceManager.againFieldInstance(savedInstanceState, this)
        mObjectInstanceManager.againFragmentInstance(childFragmentManager, this)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mObjectInstanceManager.saveField(outState, this)
    }

    protected open fun showLoading() {
        showLoading("加载中...")
    }

    protected open fun showLoading(text: String?) {
        if (mLoadingDialog != null && !mLoadingDialog!!.isShowing) {
            setLoadingText(text)
            mLoadingDialog!!.show()
        }
    }

    protected open fun hideLoading() {
        if (mLoadingDialog != null && mLoadingDialog!!.isShowing) {
            mLoadingDialog!!.dismiss()
        }
    }

    protected open fun setLoadingText(loadingText: String?) {
        mLoadingDialog!!.setLoadingText(loadingText)
    }

    protected open fun isLoading(): Boolean {
        return mLoadingDialog != null && mLoadingDialog!!.isShowing
    }

    protected open fun toast(msg: CharSequence?) {
        viewDelegate.toast(msg)
    }

    protected open fun toastError(throwable: Throwable?) {
        if(throwable == null) return
        val responseThrowable: ExceptionHandle.ResponeThrowable = ExceptionHandle.handleException(throwable, context?.applicationContext)
        viewDelegate.toast(String.format(Locale.CHINA, "%s(%d)", responseThrowable.message, responseThrowable.getCode()))
    }
}